// im.js - 腾讯IM模块
import tim from '@/common/utils/tim';
import TIM from '@/common/utils/tim';

const state = {
  isLoggedIn: false, // IM登录状态
  isSDKReady: false, // IM SDK是否准备好
  currentConversation: null, // 当前会话
  conversationList: [], // 会话列表
  currentMessageList: [], // 当前会话的消息列表
  nextReqMessageID: '', // 下一条消息的ID
  isCompleted: false, // 当前会话消息是否已经请求完毕
  unreadCount: 0 // 未读消息数
};

const mutations = {
  // 更新IM登录状态
  updateLoginStatus(state, status) {
    state.isLoggedIn = status;
  },
  
  // 更新SDK准备状态
  updateSDKReady(state, status) {
    state.isSDKReady = status;
  },
  
  // 更新当前会话
  updateCurrentConversation(state, conversation) {
    state.currentConversation = conversation;
  },
  
  // 更新会话列表
  updateConversationList(state, conversationList) {
    state.conversationList = conversationList;
  },
  
  // 将新会话添加到会话列表
  addConversation(state, conversation) {
    state.conversationList.push(conversation);
  },
  
  // 从会话列表中删除会话
  deleteConversation(state, conversationID) {
    state.conversationList = state.conversationList.filter(
      item => item.conversationID !== conversationID
    );
  },
  
  // 更新消息列表
  updateMessageList(state, messageList) {
    state.currentMessageList = messageList;
  },
  
  // 将新消息添加到消息列表
  pushCurrentMessageList(state, message) {
    state.currentMessageList = [...state.currentMessageList, message];
  },
  
  // 重置当前会话的消息列表
  resetCurrentMessageList(state) {
    state.currentMessageList = [];
  },
  
  // 更新下一条消息的ID
  updateNextReqMessageID(state, nextReqMessageID) {
    state.nextReqMessageID = nextReqMessageID;
  },
  
  // 更新消息是否已请求完毕的状态
  updateIsCompleted(state, isCompleted) {
    state.isCompleted = isCompleted;
  },
  
  // 更新未读消息数
  updateUnreadCount(state, count) {
    state.unreadCount = count;
  }
};

const getters = {
  // 获取IM登录状态
  isLoggedIn: state => state.isLoggedIn,
  
  // 获取SDK准备状态
  isSDKReady: state => state.isSDKReady,
  
  // 获取当前会话
  currentConversation: state => state.currentConversation,
  
  // 获取会话列表
  conversationList: state => state.conversationList,
  
  // 获取当前会话的消息列表
  currentMessageList: state => state.currentMessageList,
  
  // 获取未读消息数
  unreadCount: state => state.unreadCount
};

const actions = {
  // 登录IM
  async loginIM({ commit }, { userID, userSig }) {
    try {
      await tim.login({ userID, userSig });
      commit('updateLoginStatus', true);
      return true;
    } catch (error) {
      console.error('IM登录失败', error);
      return false;
    }
  },
  
  // 登出IM
  async logoutIM({ commit }) {
    try {
      await tim.logout();
      commit('updateLoginStatus', false);
      commit('updateSDKReady', false);
      return true;
    } catch (error) {
      console.error('IM登出失败', error);
      return false;
    }
  },
  
  // 获取会话列表
  async getConversationList({ commit }) {
    try {
      const { data: { conversationList } } = await tim.getConversationList();
      commit('updateConversationList', conversationList);
      
      // 计算未读消息总数
      let unreadCount = 0;
      conversationList.forEach(conversation => {
        unreadCount += conversation.unreadCount;
      });
      commit('updateUnreadCount', unreadCount);
      
      return conversationList;
    } catch (error) {
      console.error('获取会话列表失败', error);
      return [];
    }
  },
  
  // 获取指定会话的消息列表
  async getMessageList({ commit, state }, conversationID) {
    try {
      const { data: { messageList, nextReqMessageID, isCompleted } } = await tim.getMessageList({
        conversationID,
        count: 15 // 一次获取15条消息
      });
      
      commit('updateMessageList', messageList);
      commit('updateNextReqMessageID', nextReqMessageID);
      commit('updateIsCompleted', isCompleted);
      
      return messageList;
    } catch (error) {
      console.error('获取消息列表失败', error);
      return [];
    }
  },
  
  // 发送消息
  async sendMessage({ commit }, messageOptions) {
    try {
      const message = tim.createTextMessage(messageOptions);
      const { data: { message: sendResult } } = await tim.sendMessage(message);
      commit('pushCurrentMessageList', sendResult);
      return sendResult;
    } catch (error) {
      console.error('发送消息失败', error);
      return null;
    }
  },
  
  // 加入群聊
  async joinGroup({ commit }, groupID) {
    try {
      console.log('开始加入群聊:', groupID);
      
      // 先尝试不指定类型参数
      let joinOptions = {
        groupID: groupID
      };
      
      // 如果群ID包含特定标识，可以添加类型参数
      if (groupID.includes('AVChatRoom') || groupID.includes('avchatroom')) {
        joinOptions.type = 'AVChatRoom';
      } else if (groupID.includes('Private') || groupID.includes('private')) {
        joinOptions.type = 'Private';
      } else {
        // 对于普通群聊，尝试使用 Public 类型
        joinOptions.type = 'Public';
      }
      
      console.log('加入群聊参数:', joinOptions);
      
      const { data } = await tim.joinGroup(joinOptions);
      console.log('加入群聊成功', data);
      if(data.status=='WaitAdminApproval'){
		  console.log(132)
		  data.status='请等待管理员批准'
		  return { success: false, data}
	  }
      // 加入成功后，等待一段时间确保群聊状态更新
      await new Promise(resolve => setTimeout(resolve, 1000));
      
      return { success: true, data };
    } catch (error) {
      console.error('加入群聊失败', error);
      
      // 如果带类型参数失败，尝试不带类型参数
      if (joinOptions.type) {
        console.log('尝试不带类型参数加入群聊');
        try {
          const { data } = await tim.joinGroup({
            groupID: groupID
          });
          console.log('不带类型参数加入群聊成功', data);
          await new Promise(resolve => setTimeout(resolve, 1000));
          return { success: true, data };
        } catch (retryError) {
          console.error('不带类型参数加入群聊也失败', retryError);
          return { success: false, error: retryError };
        }
      }
      
      return { success: false, error };
    }
  },
  
  // 获取群列表
  async getGroupList({ commit }) {
    try {
      const { data } = await tim.getGroupList();
      return { success: true, data: data.groupList };
    } catch (error) {
      console.error('获取群列表失败', error);
      return { success: false, error };
    }
  },
  
  // 获取群资料
  async getGroupProfile({ commit }, groupID) {
    try {
      const { data } = await tim.getGroupProfile({
        groupID: groupID
      });
      return { success: true, data };
    } catch (error) {
      console.error('获取群资料失败', error);
      return { success: false, error };
    }
  },
  
  // 验证是否为群成员
  async verifyGroupMember({ commit }, groupID) {
    try {
      const result = await this.dispatch('im/getGroupProfile', groupID);
      if (result.success) {
        console.log('群成员身份验证成功');
        return true;
      } else {
        console.log('群成员身份验证失败:', result.error);
        return false;
      }
    } catch (error) {
      console.error('验证群成员身份失败', error);
      return false;
    }
  },
  
  // 创建群聊
  async createGroup({ commit }, groupOptions) {
    try {
      console.log('开始创建群聊:', groupOptions);
      const { data } = await tim.createGroup({
        type: groupOptions.type || 'Public',
        name: groupOptions.name || '活动群聊',
        groupID: groupOptions.groupID,
        introduction: groupOptions.introduction || '活动交流群',
        notification: groupOptions.notification || '欢迎加入活动群聊',
        avatar: groupOptions.avatar || '',
        maxMemberNum: groupOptions.maxMemberNum || 200
      });
      console.log('创建群聊成功', data);
      return { success: true, data };
    } catch (error) {
      console.error('创建群聊失败', error);
      return { success: false, error };
    }
  }
};

export default {
  namespaced: true,
  state,
  mutations,
  getters,
  actions
};